package com.cmcc.driver.ui.main.adapter

import android.content.Context
import android.os.Build
import android.os.CountDownTimer
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.driver.R
import com.cmcc.driver.config.DriverPath
import com.cmcc.driver.data.entity.Order
import com.cmcc.driver.databinding.ListItemOrderReceiveBinding
import com.cmcc.shared.utils.SpHelper
import com.cmcc.shared.utils.TextViewUtil.setTextViewByLimit
import com.cmcc.shared.utils.TextViewUtil.setTextViewValue
import com.cmcc.shared.utils.TimeUtils
import com.cmcc.shared.utils.TimeUtils.getTimeGap
import com.cmcc.shared.utils.clickWithTrigger

class OrderReceiveAdapter : ListAdapter<Order, OrderReceiveViewHolder>(
    OrderReceiveDiffCallback()
) {


    private lateinit var context: Context
    private val countDownMap: SparseArray<CountDownTimer>? = SparseArray()
    private var hasOrderDoing = false

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrderReceiveViewHolder {
        this.context = parent.context
        return OrderReceiveViewHolder(
            ListItemOrderReceiveBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    fun setHasOrderDoing(isDoing: Boolean) {
        hasOrderDoing = isDoing
    }

    fun cancelTimers() {
        if (countDownMap == null) {
            return
        }
        for (i in 0 until countDownMap.size()) {
            val cdt = countDownMap.get(countDownMap.keyAt(i))
            cdt?.cancel()
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onBindViewHolder(holder: OrderReceiveViewHolder, position: Int) {
        val model = getItem(position)

        var countDownTimer: CountDownTimer? =
            countDownMap?.get(holder.binding.orderStatus.hashCode())
        countDownTimer?.cancel()

        if(model.type == 1){
            holder.binding.orderStatus.text = getTimeGap(context, model.createTime ?: "")

            countDownTimer = object : CountDownTimer(15 * 60 * 1000L, 1000L) {
                override fun onTick(millisUntilFinished: Long) {
                    holder.binding.orderStatus.text = getTimeGap(context, model.createTime ?: "")
                }

                override fun onFinish() {

                }
            }.start()
        }else{
            holder.binding.orderStatus.text =
                TimeUtils.getOverTimeGap(context, model.startTime ?: "")

            countDownTimer = object : CountDownTimer(60 * 60 * 1000L, 1000L) {
                override fun onTick(millisUntilFinished: Long) {
                    holder.binding.orderStatus.text =
                        TimeUtils.getOverTimeGap(context, model.startTime ?: "")
                }

                override fun onFinish() {

                }
            }.start()
        }

        countDownMap?.put(holder.binding.orderStatus.hashCode(), countDownTimer)

        var type = SpHelper.getParam(context, "Mode", "type", "1")

        //当前是夜间模式 设置成白天模式
        if (type == "1") {
            if (model?.type == 1) {
                holder.binding.orderType.setTextColor(ContextCompat.getColor(context, R.color.driver_tip_text_color))
            }else {
                holder.binding.orderType.setTextColor(ContextCompat.getColor(context, R.color.driver_colorBase))
            }
        }else {
            holder.binding.orderType.setTextColor(ContextCompat.getColor(context, R.color.driver_switch))
        }

        setTextViewByLimit(
            holder.binding.orderType,
            model?.type == 1,
            context.getString(R.string.driver_real_time_order),
            context.getString(R.string.driver_reservation_order)
        )

        setTextViewByLimit(
            holder.binding.options.textView3,
            model?.type == 1,
            context.getString(R.string.time_real_time),
            context.getString(R.string.order_create_time, model?.startTime)
        )


        holder.binding.direction.directionStart.text = model.startAddress
        holder.binding.direction.directionEnd.text = model.endAddress

        setTextViewValue(
            context,
            holder.binding.options.tunnel,
            R.string.order_tunnel,
            model?.tunnelName,
            context.getString(R.string.what_ever)
        )


//        setTextViewValue(
//            context,
//            holder.binding.options.tip,
//            R.string.order_tip,
//            model?.bountyFee,
//            "0.00"
//        )


        if(model.bountyFee==null){
            holder.binding.options.tip.text = context.resources.getString(R.string.driver_tip)+"HK\$ "+"0.00"
        }
        else{
            holder.binding.options.tip.text = context.resources.getString(R.string.driver_tip)+"HK\$ "+model.bountyFee.toString()+""
        }


        setTextViewValue(
            context,
            holder.binding.options.station,
            R.string.order_station,
            if (model.stationIndex.isNullOrEmpty() || model?.stationIndex == "0") null else model?.stationIndex,
            if (model.stationIndex.isNullOrEmpty() || model?.stationIndex == "0") context.getString(R.string.what_ever) else null
        )

        setTextViewValue(
            context,
            holder.binding.options.remarks,
            R.string.order_remark,
            model?.remark,
            context.getString(R.string.none)
        )

        if (model.type== 1 && hasOrderDoing) {
            holder.binding.receiveOrder.isEnabled = false
            holder.binding.receiveOrder.setBackgroundResource(R.drawable.shape_button_gray_with_corner_x25)
        } else {
            holder.binding.receiveOrder.isEnabled = true
            holder.binding.receiveOrder.setBackgroundResource(R.drawable.shape_button_accent_with_corner_x25)
        }
        holder.binding.receiveOrder.clickWithTrigger {
            mListener.onReceiveClick(model?.id ?: "", model?.type ?: 1)
        }

        holder.binding.root.clickWithTrigger {
            ARouter.getInstance().build(DriverPath.ORDER_RECEIVE_DETAIL)
                .withString("orderId", model.id).navigation()
        }
    }

    private lateinit var mListener: OnReceiveListener

    interface OnReceiveListener {
        fun onReceiveClick(orderId: String, orderType: Int)
    }

    fun setOnReceiveListener(mListener: OnReceiveListener) {
        this.mListener = mListener
    }

}

class OrderReceiveDiffCallback : DiffUtil.ItemCallback<Order>() {
    override fun areItemsTheSame(oldItem: Order, newItem: Order): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: Order, newItem: Order): Boolean {
        return oldItem.id == newItem.id
    }
}


class OrderReceiveViewHolder(val binding: ListItemOrderReceiveBinding) :
    RecyclerView.ViewHolder(binding.root) {
    fun bind() {

    }
}